<template>
  <div class="upload-item">
    <el-upload
        class="avatar-uploader"
        :action="uploadUrl"
        :headers="headers"
        :show-file-list="false"
        :on-success="handleSuccess"
        :before-upload="beforeUpload">
      <img v-if="imageUrl" :src="fullImageUrl" class="avatar">
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
    <p>当前图片地址: {{ fullImageUrl || '暂无图片' }}</p> <!-- 调试信息 -->
  </div>
</template>

<script>
import { Plus } from '@element-plus/icons-vue';

const baseUrl = 'http://localhost:9090';

export default {
  components: {
    Plus
  },
  data() {
    return {
      uploadUrl: `${baseUrl}/good/uploadImage`,
      headers: { token: sessionStorage.getItem('token') },
      imageUrl: this.propImageUrl || ''
    }
  },
  props: ['propImageUrl'],
  computed: {
    fullImageUrl() {
      if (!this.imageUrl) return '';
      const fullUrl = this.imageUrl.startsWith('http')
          ? this.imageUrl
          : `${baseUrl}${this.imageUrl}`;
      console.log('计算后的完整图片地址:', fullUrl); // 调试信息
      return fullUrl;
    }
  },
  methods: {
    handleSuccess(response, file, fileList) {
      console.log('上传成功，响应数据:', response);
      console.log('文件对象:', file);
      console.log('文件列表:', fileList);

      if (response.code === 200) {
        this.imageUrl = response.data;
        console.log('图片地址:', this.imageUrl); // 调试信息
        this.$emit('imageChange', this.imageUrl);
      } else {
        this.$message.error(response.msg || '上传失败');
      }
    },
    beforeUpload(file) {
      console.log('上传文件:', file);

      const isValidType = ['image/jpeg', 'image/png'].includes(file.type);
      const isValidSize = file.size / 1024 / 1024 < 2;

      if (!isValidType) {
        this.$message.error('仅支持 JPG/PNG 格式');
        return false;
      }
      if (!isValidSize) {
        this.$message.error('图片大小不能超过2MB');
        return false;
      }

      console.log('文件验证通过，开始上传');
      return true;
    }
  }
}
</script>